package com.founder.gateway.component.transport.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import com.founder.gateway.component.transport.netty.http.NettyHttpHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 
 * @author hfl 2018年12月4日
 */
@Configuration
@ConditionalOnClass(NettyServer.class)
@ConditionalOnProperty(value = "netty.enabled")
@ConfigurationProperties(prefix = "netty")
public class NettyServer {
	private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
	private Integer port;
	private Boolean enabled;
	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}
	

	public Boolean getEnabled() {
		return enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}


	EventLoopGroup bossGroup = new NioEventLoopGroup();
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	public void stop() throws Exception {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
	public void start() throws Exception {

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).handler(new LoggingHandler(LogLevel.DEBUG))
					.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							// server端发送的是httpResponse，所以要使用HttpResponseEncoder进行编码
//							ch.pipeline().addLast(new HttpResponseEncoder());
//							// server端接收到的是httpRequest，所以要使用HttpRequestDecoder进行解码
//							ch.pipeline().addLast(new HttpRequestDecoder());
//							ch.pipeline().addLast(new NettyHttpHandler());
//							// 增加自定义实现的Handler
//							ch.pipeline().addLast(new HttpServerCodec());
							ch.pipeline().addLast(new HttpServerCodec());
							ch.pipeline().addLast(new HttpObjectAggregator(2048));
							ch.pipeline().addLast(new NettyHttpHandler());
						}
					}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
			ChannelFuture f = b.bind(port).sync();
			logger.info("Netty started on port(s): {}", port);
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		NettyServer server = new NettyServer();
		server.setPort(8081);
		server.start();
	}
}